package db;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import boot.Boot;

public class DBReader {

	private String dbFile;
	private DBListener[] listeners;
	private int numListeners = 0;

	private FileConnection fc;
	private InputStream fis;
	private String currentString;
	private boolean fileDone;
	private boolean readInterrupted;

	public DBReader(String aDBFile) {
		dbFile = aDBFile;
		listeners = new DBListener[20];
		readInterrupted = false;
		fileDone = false;
		currentString = null;
	}

	public void addListener(DBListener listener) {
		listeners[numListeners++] = listener;
	}

	public void readDB() {
		try {

			setupInputStream();
			currentString = readFromFile();
			while ((!fileDone)  && (!readInterrupted)) {
				String title = getNextLine();
				String artist = getNextLine();
				String folder = getNextLine();
				String rating = getNextLine();
				Mp3DBRecord record = new Mp3DBRecord(title, artist,
						folder, rating);
				callListeners(record);
			}
			endListeners();

		} catch (IOException e) {
			Boot.alertException(e, this, "readDB()");
		}
	}
	
	public void stopReading() throws IOException {
		readInterrupted = true;
		closeStreams();
	}

	private void endListeners() {
		for (int i = 0; i < numListeners; i++) {
			listeners[i].readingDone();
		}
	}

	private void callListeners(Mp3DBRecord record) {
		for (int i = 0; i < numListeners; i++) {
			listeners[i].processRecord(record);
		}
	}

	private String getNextLine() throws IOException {
		String result = null;

		if ((!fileDone) && (currentString.length() < 100)) {
			currentString += readFromFile();
		}

		int returnIndex = currentString.indexOf("\r\n");
		result = currentString.substring(0, returnIndex);
		currentString = currentString.substring(returnIndex + 2, currentString
				.length());
		return result;
	}

	private void setupInputStream() throws IOException {
		fc = (FileConnection) Connector.open(dbFile);

		if (!fc.exists()) {
			throw new IOException("File does not exists");
		}
		fis = fc.openInputStream();
	}

	private String readFromFile() throws IOException {
		String result = null;
		int bufferLength = 512;
		byte[] b = new byte[bufferLength];
		int length = fis.read(b, 0, bufferLength);

		if (length > 0) {
			result = new String(b, 0, length);
			// result = new String(b, 0, length, "ISO-8859-1");
			result = replace("\t", "", result);
		} else {
			fileDone = true;
			closeStreams();
		}
		return result;
	}

	private void closeStreams() throws IOException {
		fis.close();
		fc.close();
	}

	private String replace(String expression, String replace, String input) {
		String result = input;
		int index = result.indexOf(expression);

		while (index > -1) {
			result = result.substring(0, index)
					+ replace
					+ result.substring(index + expression.length(), result
							.length());
			index = result.indexOf(expression);
		}
		return result;
	}
	
}
